import type { ChatMessageVo } from '@/api/chat/types';
import { defineStore } from 'pinia';
import { getChatList } from '@/api';
import { extractContentAfterThink, extractThinkContent } from '@/utils/contentParser';
import { useUserStore } from './user';

export const useChatStore = defineStore('chat', () => {
  const userStore = useUserStore();

  // 是否开启深度思考
  const isDeepThinking = ref<boolean>(false);

  const setDeepThinking = (value: boolean) => {
    isDeepThinking.value = value;
  };

  // 会议ID对应-聊天记录 map对象
  const chatMap = ref<Record<string, ChatMessageVo[]>>({});

  const setChatMap = (id: string, data: ChatMessageVo[]) => {
    chatMap.value[id] = data?.map((item: ChatMessageVo) => {
      const isUser = item.role === 'user';
      const thinkContent = extractThinkContent(item.content as string);
      return {
        ...item,
        key: item.id,
        placement: isUser ? 'end' : 'start',
        isMarkdown: false,
        noStyle: true,
        // variant: 'shadow',
        // shape: 'corner',
        avatar: isUser
          ? item.avatar
          : 'https://www.xqnmz.com/static/image/default.jpg',
        avatarSize: '32px',
        typing: false,
        reasoning_content: thinkContent,
        thinkingStatus: 'end',
        content: extractContentAfterThink(item.content as string),
        thinlCollapse: false,
      };
    });
  };

  // 获取当前会话的聊天记录
  const requestChatList = async (sessionId: string) => {
    // 即使没有 token 也尝试查询聊天记录（对于公开会话）
    try {
      const res = await getChatList({
        sessionId,
        // 仅在有用户信息时传递userId参数
        ...(userStore.userInfo?.userId && { userId: userStore.userInfo?.userId as number }),
      });
      if (res.data) {
        // 检查返回的数据是数组还是分页对象
        if (Array.isArray(res.data)) {
          // 直接返回数组的情况
          setChatMap(sessionId, res.data);
        }
        else if (res.data.rows) {
          // 分页结构的情况
          setChatMap(sessionId, res.data.rows);
        }
      }
    }
    catch (error) {
      // 重新抛出错误，让调用者处理
      throw error;
    }
  };

  return {
    chatMap,
    requestChatList,
    isDeepThinking,
    setDeepThinking,
  };
});
